import fetch from 'isomorphic-fetch';
import { jsonToStr } from './transfer';

function handleResponse(response) {
  const contentType = response.headers.get('content-type');
  if (contentType.includes('application/json')) {
    return handleJSONResponse(response);
  } if (contentType.includes('text/html')) {
    return handleTextResponse(response);
  }
  // Other response types as necessary. I haven't found a need for them yet though.
  throw new Error(`content-type ${contentType} not supported`);
}

function handleJSONResponse(response) {
  return response.json()
    .then((json) => {
      if (response.ok) {
        return json;
      }
      return Promise.reject({
        ...json,
        status: response.status,
        statusText: response.statusText,
      });
    });
}

function handleTextResponse(response) {
  return response.text()
    .then((text) => {
      if (response.ok) {
        return text;
      }
      return Promise.reject({
        status: response.status,
        statusText: response.statusText,
        err: text,
      });
    });
}

/* fetch参数：
  url,
  {
    method:'POST',
    body:
    headers:{'Contens-Type':'application/json'},
    mode:'cors'|'no-cors'|'same-oragin'|'navigate',
    cache
    ...
  })
  .then((data)=>{
    ...
  }).then((err)=>{
    ...
  }) 
*/

function request(param) {
  const option = [];
  if (typeof param === 'string') {
    option.push(param);
  } else if (typeof param === 'object') {
    const _param = {method:'GET',url:''};
    Object.assign(_param, param);
    const method = _param.method.toUpperCase();
    if (_param.data) {
      const dataStr = jsonToStr(_param.data);
      if (_param.data) {
        if(method === 'GET' || method === 'HEAD'){
          _param.url += (`?${dataStr}`);
        } else{
          _param.body = dataStr;
        }
      }
    }
    option.push(_param.url);
    delete _param.url;
    option.push(_param);
  }
  return fetch(...option).then(handleResponse);
}
export default request;
